

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using JTC.MiniCommerce.Core;
using JTC.MiniCommerce.Localization;
using JTC.MiniCommerce.Store;
using SubSonic;
using SubSonic.Utilities;

namespace JTC.MiniCommerce.Web.admin {
  public partial class contentedit : System.Web.UI.Page {

    #region Member Variables

    DataSet ds;

    #endregion

    #region Page Events

    /// <summary>
    /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page.
    /// </summary>
    /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param>
    protected override void OnInit(EventArgs e) {
      Session["FCKeditor:UserFilesPath"] = @"~/repository/content/";
      base.OnInit(e);
    }

    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e) {
      try {
        SetContentEditProperties();
        btnDelete.Visible = false;
        //http://aspalliance.com/822
        if(!Page.IsPostBack) {
          GetPageDataSet();
          LoadTreeView(ds);
          LoadParentPageDropDown(ds);
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(contentedit).Name + ".Page_Load", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Selected event of the Page control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Selected(object sender, EventArgs e) {
      try {
        int pageId = 0;
        int.TryParse(tvPages.SelectedNode.Value, out pageId);
        if(pageId > 0) {
          Store.Page page = new Store.Page(pageId);
          lblPageId.Text = page.PageId.ToString();
          ddlParentPage.SelectedValue = page.ParentId.ToString();
          txtTitle.Text = page.Title;
          txtMenuTitle.Text = page.MenuTitle;
          txtKeywords.Text = page.Keywords;
          txtDescription.Text = page.Description;
          txtContent.Value = HttpUtility.HtmlDecode(page.Content);
          //if not kids, then set the delete button
          PageCollection pageCollection = new PageCollection().Where(Store.Page.Columns.ParentId, Comparison.Equals, pageId).Load();
          if(pageCollection.Count == 0) {
            btnDelete.Visible = true;
          }
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(contentedit).Name + ".Page_Selected", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnDelete control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnDelete_Click(object sender, EventArgs e) {
      try {
        int pageId = 0;
        int.TryParse(lblPageId.Text, out pageId);
        if(pageId > 0) {
          Store.Page.Delete(pageId);
          GetPageDataSet();
          LoadTreeView(ds);
          LoadParentPageDropDown(ds);
          btnDelete.Visible = false;
          Reset();
          Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblPageDeleted"));
        }
      }
      catch(Exception ex) {
        Logger.Error(typeof(contentedit).Name + ".btnDelete_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnReset control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnReset_Click(object sender, EventArgs e) {
      try {
        Reset();
      }
      catch(Exception ex) {
        Logger.Error(typeof(contentedit).Name + ".btnReset_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    /// <summary>
    /// Handles the Click event of the btnSave control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
      try {
        Store.Page page;
        int parentId = 0;
        int pageId = 0;
        int.TryParse(lblPageId.Text, out pageId);
        if(pageId > 0) {
          page = new Store.Page(pageId);
        }
        else {
          page = new Store.Page();
        }
        int.TryParse(ddlParentPage.SelectedValue, out parentId);
        page.ParentId = parentId;
        page.Title = txtTitle.Text;
        page.MenuTitle = txtMenuTitle.Text;
        page.Keywords = txtKeywords.Text;
        page.Description = txtDescription.Text;
        page.Content = HttpUtility.HtmlEncode(txtContent.Value);
        page.Save(WebUtility.GetUserName());
        Reset();
        GetPageDataSet();
        LoadTreeView(ds);
        LoadParentPageDropDown(ds);
        Master.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblPageSaved"));
      }
      catch(Exception ex) {
        Logger.Error(typeof(contentedit).Name + ".btnSave_Click", ex);
        Master.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message));
      }
    }

    #endregion

    #region Methods

    #region Private

    /// <summary>
    /// Gets the page data set.
    /// </summary>
    private void GetPageDataSet() {
      ds = new Store.PageController().FetchPageList();
    }

    /// <summary>
    /// Loads the tree view.
    /// </summary>
    /// <param name="ds">The ds.</param>
    private void LoadTreeView(DataSet ds) {
      tvPages.Nodes.Clear();
      xmlDataSource.EnableCaching = false;
      xmlDataSource.Data = ds.GetXml();
    }

    /// <summary>
    /// Loads the parent page drop down.
    /// </summary>
    /// <param name="ds">The ds.</param>
    private void LoadParentPageDropDown(DataSet ds) {
      ddlParentPage.Items.Clear();
      DataRow[] rootNodes = ds.Tables["Menu"].Select("ParentId = 0");
      FillNodes(rootNodes, 1);
      ddlParentPage.Items.Insert(0, new ListItem(LocalizationUtility.GetText("lblRoot"), "0"));
    }

    /// <summary>
    /// Fills the nodes.
    /// </summary>
    /// <param name="nodes">The nodes.</param>
    /// <param name="level">The level.</param>
    private void FillNodes(DataRow[] nodes, int level) {
      DataRow[] childNodes;
      int oldLevel = level;
      string name = string.Empty;
      for(int i = 0;i <= nodes.GetUpperBound(0);i++) {
        for(int j = 0;j < level;j++) {
          name += "-";
        }
        name += nodes[i]["MenuTitle"].ToString();
        ddlParentPage.Items.Add(new ListItem(name, nodes[i]["PageId"].ToString()));
        name = string.Empty;
        childNodes = nodes[i].GetChildRows("ParentChild");
        if(childNodes.GetUpperBound(0) >= 0) {
          level = level + 1;
          FillNodes(childNodes, level);
        }
        level = oldLevel;
      }
    }

    /// <summary>
    /// Resets this instance.
    /// </summary>
    private void Reset() {
      lblPageId.Text = string.Empty;
      ddlParentPage.SelectedIndex = 0;
      txtTitle.Text = string.Empty;
      txtMenuTitle.Text = string.Empty;
      txtKeywords.Text = string.Empty;
      txtDescription.Text = string.Empty;
      txtContent.Value = string.Empty;
    }

    /// <summary>
    /// Sets the content edit properties.
    /// </summary>
    private void SetContentEditProperties() {
      LocalizationUtility.AddLabelText(lblParentPage);
      LocalizationUtility.AddHoverHelp(hlParentPageHelp);
      LocalizationUtility.AddLabelText(lblTitle);
      LocalizationUtility.AddHoverHelp(hlTitleHelp);
      LocalizationUtility.AddLabelText(lblMenuTitle);
      LocalizationUtility.AddHoverHelp(hlMenuTitleHelp);
      LocalizationUtility.AddLabelText(lblKeywords);
      LocalizationUtility.AddHoverHelp(hlKeywordsHelp);
      LocalizationUtility.AddLabelText(lblDescription);
      LocalizationUtility.AddHoverHelp(hlDescriptionHelp);
      LocalizationUtility.AddLabelText(lblContent);
      LocalizationUtility.AddHoverHelp(hlContentHelp);
      LocalizationUtility.AddPanelText(pnlCurrentPages);
      LocalizationUtility.AddPanelText(pnlEditPage);
      LocalizationUtility.AddLabelText(lblContentManagement);
      LocalizationUtility.AddButtonText(btnDelete);
      LocalizationUtility.AddButtonText(btnReset);
      LocalizationUtility.AddButtonText(btnSave);
      this.Title = LocalizationUtility.GetText("titleContentManagement");
    }

    #endregion

    #endregion

  }
}
